package com.youjiang.meeting.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.youjiang.meeting.bean.TheGameRanking;
import com.youjiang.meeting.controller.SendInformationSocket;
import com.youjiang.meeting.mapper.MsgToWallMapper;
import com.youjiang.meeting.mapper.PacketRecordMapper;
import com.youjiang.meeting.mapper.ProgramMapper;
import com.youjiang.meeting.mapper.RedpackMapper;
import com.youjiang.meeting.mapper.TUserMapper;
import com.youjiang.meeting.mapper.UserInfoMapper;
import com.youjiang.meeting.mapper.VoitInfoMapper;
import com.youjiang.meeting.mapper.VoitMapper;
import com.youjiang.meeting.mapper.WxconfigMapper;
import com.youjiang.meeting.po.MsgToWall;
import com.youjiang.meeting.po.PacketRecord;
import com.youjiang.meeting.po.PacketRecordExample;
import com.youjiang.meeting.po.Program;
import com.youjiang.meeting.po.ProgramExample;
import com.youjiang.meeting.po.Redpack;
import com.youjiang.meeting.po.RedpackExample;
import com.youjiang.meeting.po.TUser;
import com.youjiang.meeting.po.TUserExample;
import com.youjiang.meeting.po.UserInfo;
import com.youjiang.meeting.po.UserInfoExample;
import com.youjiang.meeting.po.Voit;
import com.youjiang.meeting.po.VoitExample;
import com.youjiang.meeting.po.VoitInfo;
import com.youjiang.meeting.po.VoitInfoExample;
import com.youjiang.meeting.po.Wxconfig;
import com.youjiang.meeting.po.WxconfigExample;
import com.youjiang.meeting.service.ControlService;
import com.youjiang.meeting.service.WeiXinMassegeService;
import com.youjiang.meeting.utils.EmojiFilter;
import com.youjiang.meeting.utils.EmojiUtil;
import com.youjiang.meeting.utils.TimeUtil;
import com.youjiang.meeting.utils.ToolUtils;
import com.youjiang.meeting.utils.weixin.MessageUtil;
import com.youjiang.meeting.utils.weixin.WeixinSignUtil;
import com.youjiang.meeting.utils.weixin.WeixinUtil;
import com.youjiang.meeting.utils.weixinbean.Articles;
import com.youjiang.meeting.utils.weixinbean.NewsMessage;
import com.youjiang.meeting.utils.weixinbean.ShowResult;
import com.youjiang.meeting.utils.weixinbean.TextMessage;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

/**
 * <p>
 * Title: WeiXinMassegeServiceImpl
 * </p> 
 * <p>
 * Description:TODO
 * </p> 
 * <p>
 * Company: YouJiang
 * </p> 
 */
@Service
public class WeiXinMassegeServiceImpl implements WeiXinMassegeService {
	private static String SUCCESS="success";
	private static String IMAGEPATH;
//	private static List<String> list;
	private static Map<String,String> map;	
	
//	public static Wxconfig config;
	
	@Autowired
	private WxconfigMapper wMapper;
	@Autowired
	private UserInfoMapper uMapper;
	@Autowired
	private RedpackMapper rMapper;
	@Autowired
	private PacketRecordMapper prMapper;
	@Autowired
	private VoitMapper voitMapper;
	@Autowired
	private VoitInfoMapper vInfoMapper;
	@Autowired
	private MsgToWallMapper msgMapper;
	@Autowired
	private ProgramMapper pMapper;
	
	/**
	 * 显示投票结果
	 */
	public String voteResult="";
	
	/**
	 * 投票结果内容
	 */
	public String voteContent="";
	/**
	 * 游戏答案
	 */
	public  String theGameAnswer="无";
	/**
	 * 是否开始投票
	 */
	public static boolean isVote=false;
	
	/**
	 * 后台session中登录的用户
	 */
	public static UserInfo userInfo = null;
	/**
	 * 是否开始游戏
	 */
	public static boolean isGame=false;
	/**
	 * 是否开始红包
	 */
	public static boolean isRedPack=false;
	
	/**
	 * 红包地址
	 */
	public static String theReadPackUrl=WeixinUtil.DOMAINNAME+"/control/rob.action?openid=OPENID&redpack=REDPACK&noce=NOCE";
	public static String theRedPackRob=WeixinUtil.DOMAINNAME+"/control/rob.action?openid=OPENID&redpack=REDPACK";
	public static String myUrl=WeixinUtil.DOMAINNAME+"/img/srp.png";
	/**
	 * 红包口令
	 */
	public  String redPackPass;
	private  static Pattern pattern;
	/**
	 * 将当前用户所有正在进行中的节目的id添加到list集合中
	 * 当用户点击公布结果时将list设置为空
	 */
	public static Set<Integer> set = new HashSet<>();
	@Autowired
	private ControlService cService;
	
	static{
		String path = WeiXinMassegeServiceImpl.class.getResource("/").getPath();
		
		  String os = System.getProperty("os.name");
		    if(os.toLowerCase().startsWith("win")){
		    	IMAGEPATH=path.substring(1,path.indexOf("/WEB-INF/"));
		    }else{
			IMAGEPATH=path.substring(0,path.indexOf("/WEB-INF/"));
		    }
		
		
//		list=new ArrayList<String>();
		map=new HashMap<String,String>();
		pattern = Pattern.compile("[0-9]*");
	}
	@Resource
	private TUserMapper userMapper;
	@Resource
	private ControlService controlService;
	@Resource
	private ProgramMapper programMapper;
	/**
	 * 当后台用户session失效是显示这个信息
	 */
	private String result = "投票失败,请联系管理员重新登录";
	@Override
	public String receive(Map<String, String> massege) {
		try{

			JSONObject json=new JSONObject();
			// 去到那个微信号
			String toUserName = massege.get("ToUserName");
			System.out.println("toUserName----------"+toUserName);
			// 从那个微信号发过来的
			String fromUserName = massege.get("FromUserName");
			System.out.println("FromUserName-------"+fromUserName);
			
			// 时间
			//String createTime = massege.get("CreateTime");
			// 消息类型
			String msgType = massege.get("MsgType");
			// 消息的id
			//String msgId = massege.get("MsgId");
			// 事件类型
			String event = massege.get("Event");
			if(msgType.equalsIgnoreCase("EVENT")){
				if(event.equalsIgnoreCase("CLICK")){
					Map<String,String> msg=new HashMap<String,String>();
					msg.put("FromUserName", toUserName);
					msg.put("ToUserName", fromUserName);
					msg.put("MsgType", "text");
					msg.put("Content","该服务暂时无法使用");
					msg.put("CreateTime", new Date().getTime()+"");
					return WeixinSignUtil.ArrayToXml(msg);
				}
			}
			//是否是文本信息
			if(msgType.equalsIgnoreCase("text")){
				// 消息内容
				String content = massege.get("Content");
				System.out.println("content:----------------------"+content);
				
				System.out.println("isRedPack------"+isRedPack);
				Wxconfig config = null;
				Map<Integer,HttpSession> map = ToolUtils.sessions;
				if(map.size()>0){
					//设置一个boolean,为true表示如果登录的用户id与粉丝绑定的用户id一致说明粉丝与用户绑定成功
					boolean flag = false;
					for(HttpSession session:map.values()){
						
						UserInfo info = (UserInfo) session.getAttribute("userInfo");
						System.out.println("info.id--->"+info.getId()+">>info.name---"+info.getName());
						if(info!=null){
							WxconfigExample example = new WxconfigExample();
							WxconfigExample.Criteria criteria = example.createCriteria();
							criteria.andOriginidEqualTo(toUserName);
							List<Wxconfig> wxconfigList = wMapper.selectByExample(example);
							if(wxconfigList!=null && wxconfigList.size()>0){
								config = wxconfigList.get(0);
								int userid = config.getUserid();
								//如果登录的用户id与粉丝绑定的用户id一致说明粉丝与用户绑定成功
								
								if(info.getId()==userid){
									flag = true;
									break;
								}
							}else{
								String textMessage = textMessageToUser(toUserName,fromUserName,"用户未配置成功,请联系管理员重新配置");
								return textMessage;	
							}
						}else{
							String textMessage = textMessageToUser(toUserName,fromUserName,"企业还未进行活动");
							return textMessage;	
						}
					}
					if(!flag){
						String textMessage = textMessageToUser(toUserName,fromUserName,"企业还未进行活动");
						return textMessage;	
					}
				}else{
					String textMessage = textMessageToUser(toUserName,fromUserName,"企业还未进行活动");
					return textMessage;
				}
				send(content,fromUserName,config.getAppid(),config.getApsecrect(),toUserName);
				Integer redpackId = null;
				Integer userid = config.getUserid();
				if(userid!=null){
					UserInfo info = uMapper.selectByPrimaryKey(userid);
				    if(info!=null){		
				    	/**
				    	 * 
				    	 * 红包模块功能实现
				    	 */
				    	RedpackExample rExample = new RedpackExample();
				    	RedpackExample.Criteria rCriteria = rExample.createCriteria();
				    	rCriteria.andUseridEqualTo(info.getId());
				    	List<Redpack> redPackList = rMapper.selectByExample(rExample);
				    	System.out.println("redPackList----------"+redPackList.size());
				    	if(redPackList!=null && redPackList.size()>0){
				    		for(Redpack redpack:redPackList){
	//				    		Redpack redpack = redPackList.get(0);
					    		System.out.println("redpack---------"+redpack.getLevel());
					    		if(redpack.getLevel()==1){
					    			redpackId = redpack.getId();
						    		String redPackPass = redpack.getPas();
		                            System.out.println("redPackPass--------"+redPackPass);
						    		if(redPackPass.equals(content)){
						    			PacketRecordExample packetExample = new PacketRecordExample();
						    			PacketRecordExample.Criteria packetCriteria = packetExample.createCriteria();
						    			packetCriteria.andOpenidEqualTo(fromUserName);
						    			packetCriteria.andPacketidEqualTo(redpackId);
						    			List<PacketRecord> recordList = prMapper.selectByExample(packetExample);
						    			if(recordList!=null && recordList.size()>0){
						    				return textMessageToUser(toUserName, fromUserName, "您以领取了红包，不能再次领取");
						    			}
	
						    			String redpackToUser = redpackToUser(toUserName,fromUserName,redpackId,config,redPackPass);
						   		        
										return redpackToUser;
						    		}else{
						    			return textMessageToUser(toUserName, fromUserName, "红包口令输入有误,请重新输入口令");
						    		}
					    		}
				    	}
				    	}else{
//				    		return textMessageToUser(toUserName, fromUserName, "当前没有进行中的红包,请查看当前红包的口令是否正确");
				    	}	
				    	
				    	/**
				    	 * 
				    	 * 投票模块功能实现
				    	 */
				    	ProgramExample pexample = new ProgramExample();
			    		ProgramExample.Criteria pCriteria = pexample.createCriteria();
			    		pCriteria.andUseridEqualTo(userid);
			    		//获取当前用户的界面列表
			    		List<Program> pList = programMapper.selectByExample(pexample);
			    		
			    		if(pList!=null && pList.size()>0){
			    			for(Program program:pList){
			    				VoitExample vexample = new VoitExample();
				    			VoitExample.Criteria vcriteria = vexample.createCriteria();
				    			vcriteria.andProgramidEqualTo(program.getId());
				    			//将当前正在进行的节目查询出来,以前的节目不会被查出来
//				    			vcriteria.andLevelEqualTo(1);
				    			//获取当前用户的正在进行中的所有活动对应的投票记录表(每一个活动对应一个投票记录表)
				    			List<Voit> voitList = voitMapper.selectByExample(vexample);
				    			
				    			if(voitList!=null && voitList.size()>0){
				    				
				    				Voit voit = voitList.get(0);
				    				//投票活动开始
				    				if(voit.getLevel()==1){
				    					if(content.contains("投票")){
				    						return textMessageToUser(toUserName, fromUserName, "投票活动正在进行中,请输入节目对应的序号参与投票活动,每个节目限投一次");
				    					}
				    					//将当前用户所有正在进行中的节目的id添加到list集合中
			    						getAllProgramidByUserId(pList);
				    					for(int i:set){
				    						System.out.print(i+"--");
				    					}
				    					//判断粉丝发来的序号是否是list集合中包含的id
				    					try{
				    						if(set.contains(Integer.parseInt(content))){
					    						VoitInfoExample vInfoexample = new VoitInfoExample();
					    						VoitInfoExample.Criteria vInfocriteria = vInfoexample.createCriteria();
					    						//使用节目id和粉丝的openid作为条件查询
					    						vInfocriteria.andProgramidEqualTo(Integer.parseInt(content));
					    						vInfocriteria.andOpenidEqualTo(fromUserName);
					    						List<VoitInfo> vInfoList = vInfoMapper.selectByExample(vInfoexample);
					    						System.out.println("vInfoList----"+vInfoList.size());
					    						if(vInfoList==null || vInfoList.size()<=0){
					    							VoitInfo voitinfo = new VoitInfo();
					    							voitinfo.setOpenid(fromUserName);
					    							voitinfo.setProgramid(Integer.parseInt(content));
					    							//将节目id和粉丝的openid添加到投票记录表中
					    							vInfoMapper.insert(voitinfo);
					    							return textMessageToUser(toUserName, fromUserName, "投票成功");
					    						}else{
					    							
					    							return textMessageToUser(toUserName, fromUserName, "您以投过票了,请不要重复投票");
					    						}
					    					}else{
					    						return textMessageToUser(toUserName, fromUserName, "您输入的序号有误，请重新输入");
					    					}
				    					}catch(NumberFormatException e){
				    						
				    						return textMessageToUser(toUserName, fromUserName, "请输入合法的数字");
				    					}
				    					
				    				}
				    				//显示投票结果
				    				if(voit.getLevel()==2){
				    					String msg = sendVoitResultToUser(voteResult);
				    					
				    					return textMessageToUser(toUserName, fromUserName, msg);
				    				}
			
				    			}
			    			}
			    			
			    		}		    	
				    	
				    }
				}else{
					return textMessageToUser(toUserName, fromUserName, "当前配置项的所属的用户不存在,请联系管理员重新配置");
				}
			}
			if(msgType.equalsIgnoreCase("image")){
				WxconfigExample example = new WxconfigExample();
				WxconfigExample.Criteria criteria = example.createCriteria();
				criteria.andOriginidEqualTo(toUserName);
				List<Wxconfig> wxconfigList = wMapper.selectByExample(example);
				Wxconfig config = null;
				if(wxconfigList!=null && wxconfigList.size()>0){
					config = wxconfigList.get(0);
				}else{
					String textMessage = textMessageToUser(toUserName,fromUserName,"用户未配置成功,请联系管理员重新配置");
					return textMessage;					
				}
				String url=massege.get("MediaId");
				new SendImageThread(url, fromUserName,config.getAppid(),config.getApsecrect(),config.getOriginid()).start();
				return SUCCESS;
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 将当前用户所有正在进行中的节目的id添加到list集合中
	 * @param userid
	 */
    private void getAllProgramidByUserId(List<Program> pList) {
		// TODO Auto-generated method stub
    	for(Program pro:pList){
    		VoitExample voiexample = new VoitExample();
    		VoitExample.Criteria criteria = voiexample.createCriteria();
    		criteria.andProgramidEqualTo(pro.getId());
    		List<Voit> voiList = voitMapper.selectByExample(voiexample);
    		if(voiList!=null && voiList.size()>0){
    			Voit i = voiList.get(0);
    			if(i.getLevel()==1){
    				set.add(pro.getId());
    			}
    		}
    	}
	}

	/**
     * 将领取红包的接口发送到用户微信客户端,用户点击这个接口可以领红包		
     * @param toUserName
     * @param fromUserName
     * @param redPackPass2
     * @param redpackId 
     * @param config 
	 * @param redPackPass 
     * @return
     */
	private String redpackToUser(String toUserName, String fromUserName, Integer redpackId, Wxconfig config, String redPackPass) {
		// TODO Auto-generated method stub
		System.out.println("--"+config.getAppid());
		System.out.println("--"+config.getApsecrect());
		NewsMessage newsMessage=new NewsMessage();
		newsMessage.setArticleCount(1);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setFromUserName(toUserName);//客户公众号id
		newsMessage.setToUserName(fromUserName);//粉丝在客户公众号的openId
		newsMessage.setMsgType("news");
		Articles articles=new Articles();
		articles.setDescription("红包（注：转发无效）");
		articles.setTitle(redPackPass);
		articles.setPicUrl(myUrl);
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
                + "wxd34555efeb5ce59f"
                + "&redirect_uri="
                + "http://v.szweij.com/meeting/authorization.action"
                + "&response_type=code&scope=snsapi_userinfo&state="+toUserName+"("+redpackId+")"+config.getAppid()+"*"+config.getApsecrect()+"#wechat_redirect";
		articles.setUrl(url);
		newsMessage.setArticles(articles);
		String data= WeixinSignUtil.articlesToItem(newsMessage);
		return data;
	}

	/**
	 * 返回给用户的消息
	 * @param toUserName
	 * @param fromUserName
	 * @param string
	 * @return
	 */
	private String textMessageToUser(String toUserName,String fromUserName,String content) {
		TextMessage text = new TextMessage();
		text.setContent(content);
		text.setCreateTime(new Date().getTime());
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType("text");
		text.setMsgId("1232432");
		return MessageUtil.textMessageToXML(text);
	}

	public void send(String content,String openid, String appid, String appsecrect,String origined){
		new SendThread(content,openid,appid,appsecrect,origined).start();
	}
	
	class SendImageThread extends Thread{
		private String mediaId;
		private String openid;
		private String appid;
		private String appsecrect;
		private String origined;
		public SendImageThread(String mediaId,String openid, String appid, String appsecrect,String origined) {
			this.mediaId=mediaId;
			this.openid=openid;
			this.appid = appid;
			this.appsecrect = appsecrect;
			this.origined = origined;
		}
		@Override
		public void run() {
			String path="/upload/";
			try {
				JSONObject json=new JSONObject();
				MsgToWall user = msgMapper.selectByOpenid(openid);
				
				if(user!=null){
					json.put("name", user.getNickname());
					json.put("head",user.getHead());
					json.put("type", 1002);
					json.put("sendtime", TimeUtil.getCurrentTimeString());
					json.put("origined", origined);
					String picurl = WeixinUtil.downloadMedia(mediaId,IMAGEPATH+path,appid,appsecrect);
					if(StringUtils.isEmpty(picurl)){
						return ;
					}
					json.put("picurl", path+picurl);
					System.out.println("json-----------"+json);
					SendInformationSocket.send(json.toString());
				}else{
					JSONObject fromOpenid = WeixinUtil.toUserFromOpenid(openid,appid,appsecrect);
					if(fromOpenid==null){
						return ;
					}
					int subscribe=fromOpenid.optInt("subscribe", -1);
					if(subscribe==1){
						user =new MsgToWall();
						String head=fromOpenid.optString("headimgurl");
						user.setNickname(EmojiFilter.filterEmoji(fromOpenid.optString("nickname","昵称获取失败")) ); 
						user.setHead(head.substring(0, head.lastIndexOf("/0"))+"/132");
						user.setOpenid(openid);
						try{
							msgMapper.insert(user);
						}catch(Exception e){
						e.printStackTrace();
						}
						json.put("name", user.getNickname());
						json.put("head", user.getHead());
						json.put("type", 1002);
						json.put("sendtime", TimeUtil.getCurrentTimeString());
						String picurl = WeixinUtil.downloadMedia(mediaId,IMAGEPATH+path,appid,appsecrect);
						if(StringUtils.isEmpty(picurl)){
							return ;
						}
						json.put("picurl", path+picurl);
						SendInformationSocket.send(json.toString());
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	class SendThread extends Thread{
		private String content="";
		private String openid;
		private String appid;
		private String appsecrect;
		private String origined;
		public SendThread(String content,String openid, String appid, String appsecrect,String origined) {
			this.content=content;
			this.openid=openid;
			this.appid = appid;
			this.appsecrect = appsecrect;
			this.origined = origined;
		}
		@Override
		public void run() {
			if(!StringUtils.isEmpty(openid)){
				JSONObject json=new JSONObject();
				MsgToWall user = msgMapper.selectByOpenid(openid);
				if(user!=null){
					json.put("origined", origined);
					json.put("name", user.getNickname());
					json.put("head",user.getHead());
					json.put("sendtime", TimeUtil.getCurrentTimeString());
					json.put("type", 1001);
					json.put("content", content);
//					ProgramExample pexample = new ProgramExample();
//					ProgramExample.Criteria pCriteria = pexample.createCriteria();
//					pCriteria.andUseridEqualTo(userid);
//					List<Program> pList = pMapper.selectByExample(pexample);
//					if(){
//				    }
//					VoitExample example = new VoitExample();
//					VoitExample.Criteria criteria = example.createCriteria();
//					voitMapper.selectByExample(example);
//					if(isVote){
						if(!pattern.matcher(content).matches()){
							SendInformationSocket.send(json.toString());
						}
//					}else{
//						SendInformationSocket.send(json.toString());
//					}
				}else{
					try {
						JSONObject fromOpenid = WeixinUtil.toUserFromOpenid(openid,appid,appsecrect);
						if(fromOpenid==null){
							return ;
						}
						int subscribe=fromOpenid.optInt("subscribe", -1);
						if(subscribe==1){
							String head=fromOpenid.optString("headimgurl");
							String nickname=fromOpenid.optString("nickname","昵称获取失败");
							user =new MsgToWall();
							user.setNickname(EmojiFilter.filterEmoji(nickname)); 
							if(!StringUtils.isEmpty(head))
							user.setHead(head.substring(0, head.lastIndexOf("/0"))+"/132");
							user.setOpenid(openid);
							try{
								msgMapper.insert(user);
							}catch(Exception e){
								
							}
							
							json.put("name", user.getNickname());
							json.put("head", user.getHead());
							json.put("sendtime", TimeUtil.getCurrentTimeString());
							json.put("type", 1001);
							if(EmojiFilter.containsEmoji(content)){
								content = EmojiFilter.filterEmoji(content);
							}
							
							json.put("content", content);
//							if(isVote){
								if(!pattern.matcher(content).matches()){
									SendInformationSocket.send(json.toString());
								}
//							}else{
//								SendInformationSocket.send(json.toString());
//							}
						}
					} catch (ClassNotFoundException | IOException e) {
						e.printStackTrace();
					}
				}
				//数据对比
				//开始竞猜游戏
				if(isGame){
//					if(content.equals(theGameAnswer)||theGameAnswer.equals(ZHConverter.convert(content, ZHConverter.SIMPLIFIED))){
					if(content.equals(theGameAnswer)||theGameAnswer.equals(content)){
						TheGameRanking ranking=new TheGameRanking();
						ranking.setHead(user.getHead());
						ranking.setNickname(user.getNickname());
						ranking.setTime(new Date().getTime());
						ranking.setCreateTime(TimeUtil.getCurrentTimeString());
						ranking.setOpenid(openid);
						controlService.addGameAnswer(ranking);
					}
				}
				if(isVote){
					String result="";
					if(pattern.matcher(content).matches()){
						result=content.trim();
					}
					if(!StringUtils.isEmpty(result)){
						controlService.addVoit(result, openid);
					}
				}
				
			}else{
				SendInformationSocket.send(content);
			}
		}
	}

	@Override
	public ModelAndView authorization(String code, String state, boolean isInfo,HttpServletRequest req) {
		//state="+toUserName+"%"+redpackId+"%"+config.getAppid()+"*"+config.getApsecrect()
		
		System.out.println("state------"+state);
		String toUserName = (String) state.subSequence(0, state.indexOf("("));
		String redpackId = (String) state.subSequence(state.indexOf("(")+1, state.indexOf(")"));
		String appid = (String) state.subSequence(state.indexOf(")")+1, state.indexOf("*"));
		System.out.println("appid----------"+appid);
		String apsecrect = state.substring(state.indexOf("*")+1);
		System.out.println("apsecrect-----------"+apsecrect);
		System.out.println("isInfo--------------"+isInfo);
		if(isInfo){
			System.out.println("code-------------"+code);
			if(!StringUtils.isEmpty(code)){
				
				try {
					JSONObject info = WeixinUtil.weixinCodeToInfo(code, true ,req,appid,apsecrect);
					String openid= info.optString("openid", null);
					System.out.println("openid-----------"+openid);
					if(!StringUtils.isEmpty(openid)){
						TUserExample ex=new TUserExample();
						ex.createCriteria().andOpenidEqualTo(openid);
						List<TUser> selectByExample = userMapper.selectByExample(ex);
						if(selectByExample.size()==0){
							WxconfigExample example = new WxconfigExample();
							WxconfigExample.Criteria criteria = example.createCriteria();
							criteria.andAppidEqualTo(appid);
							List<Wxconfig> config = wMapper.selectByExample(example);
							if(config!=null && config.size()>0){
								Wxconfig wx = config.get(0);
								int userid = wx.getUserid();
								TUser user=new TUser();
								user.setUserid(userid);
								user.setOpenid(openid);
								user.setHead(info.optString("headimgurl"));
								user.setNickname(info.optString("nickname"));
								userMapper.insert(user);
							}
							
							
						}
						///send/redpack
						System.out.println("state-----------"+state);
						if(!StringUtils.isEmpty(state)){
							//state表示微信公众号名，通过该参数来区分不同微信公众号里的粉丝
							ModelAndView model = new ModelAndView();						
						    //control/send/redpack.action
							//调用请求红包接口返回值为红包金额，然后将该金额添加到url的参数上
							String money = cService.requestRedPack(openid, Integer.parseInt(redpackId), req);
//							int money = (int) req.getAttribute("money");
							System.out.println("money-----------"+money);
							/**
							 * 
							 * 
							 *可能会有并发的情况出现 
							 * 
							 * 
							 * 
							 */
							String url = "http://v.szweij.com/meeting/control/send/redpack.action?id="+redpackId+"&openid="+openid+"&money="+money;
							System.out.println("url----------------------"+url);
							model.addObject("url", url);
							model.setViewName("getRedpackInterface");
							JSONObject obj = new JSONObject();
							return model;
						}
						return null;
					}else{
						return null;
					}
				} catch (ParseException | IOException e) {
					e.printStackTrace();
				}
			}else{
			
			}
		}else{
			if(StringUtils.isEmpty(code)){
				try {
					JSONObject info = WeixinUtil.weixinCodeToInfo(code, true,req,appid,apsecrect);
					String openid= info.optString("openid", null);
					if(!StringUtils.isEmpty(openid)){
						
						return null;
						
					}else{
						return null;
					}
				} catch (ParseException | IOException e) {
					
					e.printStackTrace();
				}
		
			}
			
		}
		return null;
	}

	@Override
	public void setVoit(UserInfo info,boolean voit) {
		WeiXinMassegeServiceImpl.userInfo = info;
		isVote=voit;
	}
	@Override
	public void setGame(boolean game) {
		isGame=game;
	}

	@Override
	public void setRed(boolean red) {
		isRedPack=red;
	}

	@Override
	public void setVoteContent(String content) {
		voteContent=content;
	}
	@Override
	public void setTheGameAnswer(String answer) {
		theGameAnswer=answer;
	}

	@Override
	public void setRedPackPass(String pass) {
		redPackPass=pass;
	}
	@Override
	public boolean getVoit( ) {
		return isVote;
	}
	@Override
	public boolean getGame() {
		return isGame;
	}
	@Override
	public boolean getRed() {
		return isRedPack;
	}

	@Override
	public String sendVoitResultToUser(String json) {
		this.voteResult = json;
		// TODO Auto-generated method stub
		JSONObject object = JSONObject.fromObject(voteResult);
		
		JSONObject array = (JSONObject) object.opt("result");
		Map<Object,Object> map = array;
		if(map!=null && map.size()>0){
			String voit = "投票结果：\n";
			for(Object name:map.keySet()){
				JSONObject ob = (JSONObject) map.get(name);
				ShowResult result = (ShowResult) JSONObject.toBean(ob, ShowResult.class);
				if(result!=null){
					String name1 = result.getName();
					String principal = result.getPrincipal();
					int size = result.getSize();
					voit += "节目: "+name1+ "的主持人是: "+principal+" 获得的票数是: "+size+" 票\n";
				}
				
			}
			voit+="投票完成后,请联系主持人关闭投票操作,这样您就可以把想要说的话显示在墙上了\n";
			return voit;
		}
		
		
		return "";
		
	}

	
}
